﻿using System.ComponentModel;

namespace LvcChong
{
    public partial class FormUserOrderQuery : Form
    {
        private BindingList<OrderQueryOutput> _sourceCharge = new BindingList<OrderQueryOutput>();
        private BindingList<UserInfoOutput> _sourceUser = new BindingList<UserInfoOutput>();
        private LayerHelper _layerHelper = new LayerHelper();

        public FormUserOrderQuery()
        {
            InitializeComponent();
            pagerUser.OnPageChanged += PagerUser_OnPageChanged;
            pagerUser.OnPageSizeChanged += PagerUser_OnPageSizeChanged;
            pagerCharge.OnPageChanged += PagerCharge_OnPageChanged;
            pagerCharge.OnPageSizeChanged += PagerCharge_OnPageSizeChanged;

            InitUserGridLayout();
            InitChargeGridLayout();

            InitData();
        }

        private void PagerCharge_OnPageSizeChanged(object? sender, EventArgs e)
        {
            pagerCharge.Tag = null;
        }

        private void PagerUser_OnPageSizeChanged(object? sender, EventArgs e)
        {
            pagerUser.Tag = null;
        }

        public FormUserOrderQuery(string userId, QueryType queryType = QueryType.ID) : this()
        {
            txtValue.Text = userId;
            cboQueryType.Value = queryType;
        }

        private void PagerUser_OnPageChanged(object? sender, EventArgs e)
        {
            RefreshUserData();
        }

        private void PagerCharge_OnPageChanged(object? sender, EventArgs e)
        {
            RefreshChargeData();
        }

        private void InitUserGridLayout()
        {
            gridUser.InitializeRow += (s, e) =>
            {
                var item = e.Row.ListObject as UserInfoOutput;
                if (item == null) return;

                if (item.inTime.ParseToLong(0) != 0)
                {
                    var time = item.inTime.ParseToLong().ToDateTimeFromMilliseconds();
                    if (time != null)
                        e.Row.Cells[nameof(OrderQueryOutput.inTime)].Value = time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                }
            };

            var displayCol = new List<UltraGridDisplayItem> {
                new UltraGridDisplayItem{ Key=nameof(UserInfoOutput.id), Caption="用户编号", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(UserInfoOutput.userName), Caption="用户名称", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(UserInfoOutput.level), Caption="用户等级", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(UserInfoOutput.phone), Caption="手机号", Position=2,ColumnWidth =120},
                new UltraGridDisplayItem{ Key=nameof(UserInfoOutput.inTime), Caption="创建时间", Position=2,ColumnWidth =180},
            };

            gridUser.SetDataBinding(_sourceUser, null);
            UltraGridHelper.InitializeUltraGridDisplay(gridUser, displayCol, true, new UltraGridOptions
            {
                EnableFixedHeader = true,
                EnableExport = true,
                ShowSummary = true,
                EnableFilter = true,
            });

            gridUser.DisplayLayout.NoDataSourceMessageEnabled = Infragistics.Win.DefaultableBoolean.False;
            gridUser.DisplayLayout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.None;

            gridUser.DisplayLayout.Override.RowAlternateAppearance.BackColor = Color.FromArgb(244, 244, 244);
        }

        private void InitChargeGridLayout()
        {
            grid.InitializeRow += (s, e) =>
            {
                var item = e.Row.ListObject as OrderQueryOutput;
                if (item == null) return;

                if (item.actualTime == null) e.Row.Cells[nameof(OrderQueryOutput.actualTime)].Value = "未结束";
                if (item.actualElectricQuantity == null) e.Row.Cells[nameof(OrderQueryOutput.actualTime)].Value = "未上报";

                if (item.inTime.ParseToLong(0) != 0)
                {
                    var time = item.inTime.ParseToLong().ToDateTimeFromMilliseconds();
                    if (time != null)
                        e.Row.Cells[nameof(OrderQueryOutput.inTime)].Value = time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                }

                if (item.updateTime.ParseToLong(0) != 0)
                {
                    var time = item.updateTime.ParseToLong().ToDateTimeFromMilliseconds();
                    if (time != null)
                        e.Row.Cells[nameof(OrderQueryOutput.updateTime)].Value = time.Value.ToString("yyyy-MM-dd HH:mm:ss");
                }
            };

            var displayCol = new List<UltraGridDisplayItem> {
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.orderNum), Caption="订单号", Position=2,ColumnWidth =200},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.orderType), Caption="订单类型", Position=2,ColumnWidth =120},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.userId), Caption="用户编号", Position=2,ColumnWidth =120},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.userPhone), Caption="手机号", Position=2,ColumnWidth =120},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.licenseNum), Caption="车牌号", Position=2,ColumnWidth =100},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.vinNum), Caption="VIN", Position=2,ColumnWidth =180},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.deviceName), Caption="设备机号", Position=5,ColumnWidth =120},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.portNum), Caption="插座", Position=5,ColumnWidth =100},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.payPrice), Caption="消费金额", Position=5,ColumnWidth =100},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.totalElectricMoney), Caption="电费", Position=5,ColumnWidth =100},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.totalServiceFee), Caption="服务费", Position=5,ColumnWidth =100},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.payWay), Caption="支付方式", Position=5,ColumnWidth =120},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.isCount), Caption="交易状态", Position=5,ColumnWidth =120},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.status), Caption="充电状态", Position=5,ColumnWidth =150},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.paymentPrice), Caption="工作时长(分钟/度/元)", Position=5,ColumnWidth =100},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.actualTime), Caption="实际时长(分钟)", Position=5,ColumnWidth =100}, //actualTime == null 未结束
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.actualElectricQuantity), Caption="实际耗电(度)", Position=5,ColumnWidth =100}, // actualElectricQuantity == null 未上报
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.inTime), Caption="创建时间", Position=5,ColumnWidth =180},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.updateTime), Caption="更新时间", Position=5,ColumnWidth =180},
            new UltraGridDisplayItem{ Key=nameof(OrderQueryOutput.endType), Caption="结束原因", Position=5,ColumnWidth =180},
        };

            grid.SetDataBinding(_sourceCharge, null);
            UltraGridHelper.InitializeUltraGridDisplay(grid, displayCol, true, new UltraGridOptions
            {
                EnableFixedHeader = true,
                EnableExport = true,
                ShowSummary = false,
                EnableFilter = true,
            });

            grid.DisplayLayout.NoDataSourceMessageEnabled = Infragistics.Win.DefaultableBoolean.False;
            grid.DisplayLayout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.None;

            grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.orderType)].SetColumnValueList(ValueListAssist.EnumToValueList(typeof(OrderType)));
            grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.payWay)].SetColumnValueList(ValueListAssist.EnumToValueList(typeof(PayWay)));
            grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.isCount)].SetColumnValueList(ValueListAssist.EnumToValueList(typeof(OrderStatus)));
            grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.status)].SetColumnValueList(ValueListAssist.EnumToValueList(typeof(StatusType)));
            grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.endType)].SetColumnValueList(ValueListAssist.EnumToValueList(typeof(EndType)));

            grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.inTime)].Header.Fixed = true;
            grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.inTime)].Header.FixOnRight = Infragistics.Win.DefaultableBoolean.True;
            grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.updateTime)].Header.Fixed = true;
            grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.updateTime)].Header.FixOnRight = Infragistics.Win.DefaultableBoolean.True;

            grid.DisplayLayout.Override.RowAlternateAppearance.BackColor = Color.FromArgb(244, 244, 244);

            grid.DisplayLayout.Bands[0].SetDefaultBrandSummaryStyle();
            grid.DisplayLayout.Bands[0].AddSummary(
                Infragistics.Win.UltraWinGrid.SummaryType.Count,
                grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.orderNum)],
                 Infragistics.Win.UltraWinGrid.SummaryPosition.UseSummaryPositionColumn,
                 "总数 = {0}"
                );

            grid.DisplayLayout.Bands[0].AddSummary(
                Infragistics.Win.UltraWinGrid.SummaryType.Sum,
                grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.payPrice)],
                 Infragistics.Win.UltraWinGrid.SummaryPosition.UseSummaryPositionColumn,
                 "{0:#0.00}"
                );

            grid.DisplayLayout.Bands[0].AddSummary(
                Infragistics.Win.UltraWinGrid.SummaryType.Sum,
                grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.totalElectricMoney)],
                 Infragistics.Win.UltraWinGrid.SummaryPosition.UseSummaryPositionColumn,
                 "{0:#0.00}"
                );

            grid.DisplayLayout.Bands[0].AddSummary(
                Infragistics.Win.UltraWinGrid.SummaryType.Sum,
                grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.totalServiceFee)],
                 Infragistics.Win.UltraWinGrid.SummaryPosition.UseSummaryPositionColumn,
                 "{0:#0.00}"
                );

            grid.DisplayLayout.Bands[0].AddSummary(
                Infragistics.Win.UltraWinGrid.SummaryType.Sum,
                grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.paymentPrice)],
                 Infragistics.Win.UltraWinGrid.SummaryPosition.UseSummaryPositionColumn,
                 "{0:#0}.00"
                );

            grid.DisplayLayout.Bands[0].AddSummary(
                Infragistics.Win.UltraWinGrid.SummaryType.Sum,
                grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.actualTime)],
                 Infragistics.Win.UltraWinGrid.SummaryPosition.UseSummaryPositionColumn,
                 "{0:#0.00}"
                );

            grid.DisplayLayout.Bands[0].AddSummary(
                Infragistics.Win.UltraWinGrid.SummaryType.Sum,
                grid.DisplayLayout.Bands[0].Columns[nameof(OrderQueryOutput.actualElectricQuantity)],
                 Infragistics.Win.UltraWinGrid.SummaryPosition.UseSummaryPositionColumn,
                 "{0:#0.00}"
                );
        }

        private void InitData()
        {
            cboQueryType.SetDataSource(typeof(QueryType).EnumToNameValues(), "Caption");
            cboQueryType.SelectedIndex = 0;
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            if (txtValue.Text == string.Empty) return;
            RefreshUserData();
            RefreshChargeData();
        }

        private async void RefreshUserData()
        {
            var input = new UserInfoInput
            {
                page = pagerUser.CurrentPageNo,
                limit = pagerUser.PageSize,
                fromPage = pagerUser.CurrentPageNo - 1 <= 0 ? null : pagerUser.CurrentPageNo - 1,
                leastTotal = pagerUser.TotalRecords == 0 ? null : pagerUser.TotalRecords,
                deepPageTokenArr = pagerUser.Tag?.ToString(),
                queryType = cboQueryType.SelectedItem == null ? 1 : (int)((QueryType)cboQueryType.SelectedItem.DataValue),
                queryValue = txtValue.Text,
            };
            if (txtValue.Text.IndexOf(",") > 0)
                input.userIdList = $"[{txtValue.Text.ParseToLong()}]";

            var ret = await LayerRefreshAsync(() => GlobalContext.DataProvider.UserInfoQuery(input));

            _sourceUser.Clear();
            if (ret != null && ret.Data != null)
            {
                if (pagerUser.Tag == null)
                    pagerUser.Tag = ret.OtherMap?.deepPageToken;
                else pagerUser.Tag = pagerUser.Tag + "," + ret.OtherMap?.deepPageToken;
                pagerUser.RefreshPageData(ret.Count);
                foreach (var item in ret.Data) _sourceUser.Add(item);
            }
        }

        private async void RefreshChargeData()
        {
            var input = new UserInfoInput
            {
                page = pagerCharge.CurrentPageNo,
                limit = pagerCharge.PageSize,
                fromPage = pagerCharge.CurrentPageNo - 1 <= 0 ? null : pagerCharge.CurrentPageNo - 1,
                leastTotal = pagerCharge.TotalRecords == 0 ? null : pagerCharge.TotalRecords,
                deepPageTokenArr = pagerCharge.Tag?.ToString(),
                queryType = cboQueryType.SelectedItem == null ? 1 : (int)((QueryType)cboQueryType.SelectedItem.DataValue),
                queryValue = txtValue.Text,
            };
            if (input.queryType == 1)
            {
                input.userIdList = $"[{txtValue.Text.ParseToLong()}]";
            }

            var ret = await LayerRefreshAsync(() => GlobalContext.DataProvider.ChargeQuery(input));

            _sourceCharge.Clear();
            if (ret != null && ret.Data != null)
            {
                if (pagerCharge.Tag == null)
                    pagerCharge.Tag = ret.OtherMap?.deepPageToken;
                else pagerCharge.Tag = pagerCharge.Tag + "," + ret.OtherMap?.deepPageToken;
                pagerCharge.RefreshPageData(ret.Count);
                foreach (var item in ret.Data) _sourceCharge.Add(item);
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            cboQueryType.SelectedIndex = 0;
            txtValue.Clear();
        }

        private Task<T> LayerRefreshAsync<T>(Func<T> action)
        {
            var ret = Task.Run(() =>
            {
                try
                {
                    plQuery.UpdateUI(() => plQuery.Enabled = false);
                    _layerHelper.ShowOpaqueLayer(plGrid, 30);
                    return action();
                }
                finally
                {
                    _layerHelper.HideOpaqueLayer();
                    plQuery.UpdateUI(() => plQuery.Enabled = true);
                }
            });
            return ret;
        }
    }


}